package com.zxjbyte.yiyi.framework.common.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.zxjbyte.yiyi.framework.common.constant.Constant;
import com.zxjbyte.yiyi.framework.common.constant.Method;
import com.zxjbyte.yiyi.framework.common.core.ssl.DisableVerifyingSslTrustManager;
import com.zxjbyte.yiyi.framework.common.core.ssl.TrustAllHostnameVerifier;
import com.zxjbyte.yiyi.framework.common.domain.FileItem;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Set;

import static com.zxjbyte.yiyi.framework.common.constant.StringPool.*;

/**
 * jdk原生网络请求工具
 * @Author zhangxingjia
 * @Date 2023/3/22 11:05
 * @Version: 1.0
 */
@Slf4j
@UtilityClass
public class HttpUtil {

    // 默认连接超时时间 单位：毫秒
    private final int connect_timeout = 3000;
    // 默认请求超时时间 单位：毫秒
    private final int read_timeout = 15000;

    private SSLSocketFactory socketFactory = null;

    /**
     * 设置KeepAlive连接超时时间，一次HTTP请求完成后，底层TCP连接将尝试尽量保持该超时时间后才关闭，以便其他HTTP请求复用TCP连接
     * KeepAlive连接超时时间设置为0，表示使用默认的KeepAlive连接缓存时长（目前为5s）
     * 连接并非一定能保持指定的KeepAlive超时时长，比如服务端断开了连接
     */
    private final int keepAliveTimeout = 60;

    static {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] {DisableVerifyingSslTrustManager.INSTANCE},
                    Singleton.get(SecureRandom.class));

            ctx.getClientSessionContext().setSessionTimeout(15);
            ctx.getClientSessionContext().setSessionCacheSize(1000);

            socketFactory = ctx.getSocketFactory();
        } catch (Exception ignored) {
        }
    }

    /**
     * 执行HTTP POST 请求，发送FORM数据
     *
     * @param url            请求地址
     * @param params         请求参数
     * @return 响应字符串
     * @throws IOException
     */
    public String doPostForm(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
        return doPostForm(url, params, Constant.UTF_8, connect_timeout, read_timeout, null, 0, headers);
    }

    /**
     * 执行HTTP POST请求，发送FORM数据，可使用代理proxy。
     *
     * @param url            请求地址
     * @param params         请求参数
     * @param charset        字符集，如UTF-8, GBK, GB2312
     * @param connectTimeout 连接超时时间
     * @param readTimeout    请求超时时间
     * @param proxyHost      代理host，传null表示不使用代理
     * @param proxyPort      代理端口，传0表示不使用代理
     * @return 响应字符串
     */
    @SneakyThrows
    public String doPostForm(String url, Map<String, String> params, String charset,
                                int connectTimeout, int readTimeout, String proxyHost, int proxyPort, Map<String, String> headers) {
        String contentType = "application/x-www-form-urlencoded;charset=" + charset;
        String query = buildQuery(params, charset);
        byte[] content = {};
        if (query != null) {
            content = query.getBytes(charset);
        }
        return doPost(url, contentType, content, connectTimeout, readTimeout, proxyHost, proxyPort, headers);
    }

    /**
     * 执行HTTP POST请求。
     *
     * @param url            请求地址
     * @param contentType    请求类型
     * @param content        请求字节数组
     * @param headers        请求头
     * @return 响应字符串
     */
    public String doPost(String url, String contentType, byte[] content, Map<String, String> headers) {
        return doPost(url, contentType, content, connect_timeout, read_timeout, null, 0, headers);
    }

    /**
     * 执行HTTP POST 发送JSON数据。
     *
     * @param url            请求地址
     * @param content        请求字节数组
     * @param headers        请求头
     * @return 响应字符串
     */
    public String doPostJson(String url, byte[] content, Map<String, String> headers) {
        String contentType = "application/json;charset=UTF-8";
        return doPost(url, contentType, content, connect_timeout, read_timeout, null, 0, headers);
    }

    /**
     * 执行HTTP POST请求。
     *
     * @param url            请求地址
     * @param contentType    请求类型
     * @param content        请求字节数组
     * @param connectTimeout 连接超时时间
     * @param readTimeout    请求超时时间
     * @param proxyHost      代理host，传null表示不使用代理
     * @param proxyPort      代理端口，传0表示不使用代理
     * @return 响应字符串
     */
    @SneakyThrows
    public String doPost(String url, String contentType, byte[] content, int connectTimeout,
                                int readTimeout, String proxyHost, int proxyPort, Map<String, String> headers) {
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp;
        try {
            try {
                if(StrUtil.isNotBlank(proxyHost)){
                    conn = getConnection(new URL(url), Method.POST, contentType, proxyHost, proxyPort, headers);
                } else {
                    conn = getConnection(new URL(url), Method.POST, contentType, headers);
                }
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
            } catch (IOException e) {
                log.error("Http post request exception.", e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                out.write(content);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                log.error("http post method read response content exception.", e);
                throw e;
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();

            }
        }
        return rsp;
    }

    /**
     * 执行带文件上传的HTTP POST请求。
     *
     * @param url            请求地址
     * @param params         文本请求参数
     * @param fileParams     文件请求参数
     * @param charset        字符集，如UTF-8, GBK, GB2312
     * @param connectTimeout 连接超时时间
     * @param readTimeout    请求超时时间
     * @param proxyHost      代理host，传null表示不使用代理
     * @param proxyPort      代理端口，传0表示不使用代理
     * @return 响应字符串
     */
    @SneakyThrows
    public String doPost(String url, Map<String, String> params,
                                Map<String, FileItem> fileParams, String charset,
                                int connectTimeout, int readTimeout, String proxyHost, int proxyPort, Map<String, String> headers) {
        if (fileParams == null || fileParams.isEmpty()) {
            return doPostForm(url, params, charset, connectTimeout, readTimeout, proxyHost, proxyPort, headers);
        }

        String boundary = System.currentTimeMillis() + ""; // 随机分隔线
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp;
        try {
            try {
                String contentType = "multipart/form-data;boundary=" + boundary + ";charset=" + charset;
                if(StrUtil.isNotBlank(proxyHost)){
                    conn = getConnection(new URL(url), Method.POST, contentType, proxyHost, proxyPort, headers);
                } else {
                    conn = getConnection(new URL(url), Method.POST, contentType, headers);
                }
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
                conn.setFixedLengthStreamingMode(getTotalLength(params, fileParams, boundary, charset));
            } catch (IOException e) {
                log.error("Http post request exception.", e);
                throw e;
            }

            try {
                out = conn.getOutputStream();

                byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(charset);

                // 组装文本请求参数
                Set<Map.Entry<String, String>> textEntrySet = params.entrySet();
                for (Map.Entry<String, String> textEntry : textEntrySet) {
                    byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(),
                            charset);
                    out.write(entryBoundaryBytes);
                    out.write(textBytes);
                }

                // 组装文件请求参数
                Set<Map.Entry<String, FileItem>> fileEntrySet = fileParams.entrySet();
                for (Map.Entry<String, FileItem> fileEntry : fileEntrySet) {
                    FileItem fileItem = fileEntry.getValue();
                    byte[] fileBytes = getFileEntry(fileEntry.getKey(), fileItem.getFileName(),
                            fileItem.getMimeType(), charset);
                    out.write(entryBoundaryBytes);
                    out.write(fileBytes);
                    fileItem.writeFileContent(out);
                }

                // 添加请求结束标志
                byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(charset);
                out.write(endBoundaryBytes);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                log.error("http post method read response content exception.", e);
                throw e;
            }

        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    private byte[] getTextEntry(String fieldName, String fieldValue,
                                      String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data;name=\"");
        entry.append(fieldName);
        entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
        entry.append(fieldValue);
        return StrUtil.bytes(entry, charset);
    }

    private byte[] getFileEntry(String fieldName, String fileName, String mimeType,
                                       String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data;name=\"");
        entry.append(fieldName);
        entry.append("\";filename=\"");
        entry.append(fileName);
        entry.append("\"\r\nContent-Type:");
        entry.append(mimeType);
        entry.append("\r\n\r\n");
        return StrUtil.bytes(entry, charset);
    }

    private long getTotalLength(Map<String, String> params, Map<String, FileItem> fileParams, String boundary, String charset) {
        try {
            byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(charset);
            long length = 0;

            Set<Map.Entry<String, String>> textEntrySet = params.entrySet();
            for (Map.Entry<String, String> textEntry : textEntrySet) {
                byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(),
                        charset);
                length += entryBoundaryBytes.length + textBytes.length;
            }

            Set<Map.Entry<String, FileItem>> fileEntrySet = fileParams.entrySet();
            for (Map.Entry<String, FileItem> fileEntry : fileEntrySet) {
                FileItem fileItem = fileEntry.getValue();
                byte[] fileBytes = getFileEntry(fileEntry.getKey(), fileItem.getFileName(),
                        fileItem.getMimeType(), charset);
                length += entryBoundaryBytes.length + fileBytes.length + fileItem.fileContentLength();
            }

            byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(charset);
            length += endBoundaryBytes.length;
            return length;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 执行HTTP GET请求。
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应字符串
     */
    public String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    /**
     * 执行HTTP GET请求。
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应字符串
     */
    public String doGet(String url, Map<String, String> params, Map<String, String> headers) {
        return doGet(url, params, Constant.UTF_8, headers);
    }

    /**
     * 执行HTTP GET请求。
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param charset 字符集，如UTF-8, GBK, GB2312
     * @return 响应字符串
     */
    @SneakyThrows
    public String doGet(String url, Map<String, String> params, String charset, Map<String, String> headers) {
        HttpURLConnection conn = null;
        String rsp = null;

        try {
            String contentType = "application/x-www-form-urlencoded;charset=" + charset;
            String query = buildQuery(params, charset);
            try {
                conn = getConnection(buildGetUrl(url, query), Method.GET, contentType, headers);
            } catch (IOException e) {
                log.error("Http get request exception.", e);
                throw e;
            }

            try {
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                log.error("http get method read response content exception.", e);
                throw e;
            }

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    private HttpURLConnection getConnection(URL url, String method, String contentType,
                                                  Map<String, String> headers) throws IOException {
        return getConnection(url, method, contentType, null, headers);
    }

    private HttpURLConnection getConnection(URL url, String method, String contentType,
                                                  String proxyHost, int proxyPort,
                                                  Map<String, String> headers) throws IOException {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        return getConnection(url, method, contentType, proxy, headers);
    }

    private HttpURLConnection getConnection(URL url, String method, String contentType, Proxy proxy,
                                                   Map<String, String> headers) throws IOException {
        HttpURLConnection conn = null;
        if ("https".equals(url.getProtocol())) {
            HttpsURLConnection connHttps = null;
            if (proxy != null) {
                connHttps = (HttpsURLConnection) url.openConnection(proxy);
            } else {
                connHttps = (HttpsURLConnection) url.openConnection();
            }
            //设置不校验服务端证书的SSLContext
            connHttps.setSSLSocketFactory(socketFactory);
            connHttps.setHostnameVerifier(TrustAllHostnameVerifier.INSTANCE);
            conn = connHttps;
        } else {
            if (proxy != null) {
                conn = (HttpURLConnection) url.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
        }
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("User-Agent", Constant.DEFAULT_USER_AGENT);
        conn.setRequestProperty("Content-Type", contentType);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        return conn;
    }

    private URL buildGetUrl(String strUrl, String query) throws IOException {
        URL url = new URL(strUrl);
        if (StrUtil.isBlank(query)) {
            return url;
        }
        if (StrUtil.isBlank(url.getQuery())) {
            if (strUrl.endsWith(QUESTION_MARK)) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + QUESTION_MARK + query;
            }
        } else {
            if (strUrl.endsWith(AMPERSAND)) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + AMPERSAND + query;
            }
        }

        return new URL(strUrl);
    }

    private String buildQuery(Map<String, String> params, String charset) {
        if (params == null || params.isEmpty()) {
            return null;
        }
        return URLUtil.buildQuery(params, Charset.forName(charset));
    }

    private String getResponseAsString(HttpURLConnection conn) throws IOException {
        Charset charset = Charset.forName(getResponseCharset(conn.getContentType()));

        //此时设置KeepAlive超时所需数据结构才刚初始化完整，可以通过反射修改
        //同时也不宜将修改时机再滞后，因为可能后续连接缓存类已经消费了默认的KeepAliveTimeout值，再修改已经无效
        setKeepAliveTimeout(conn);

        InputStream es = conn.getErrorStream();
        if (es == null) {
            return IoUtil.read(conn.getInputStream(), charset);
        } else {
            String msg = IoUtil.read(es, charset);
            if (StrUtil.isBlank(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                throw new IOException(msg);
            }
        }
    }


    private String getResponseCharset(String contentType) {
        String charset = Constant.UTF_8;
        if (StrUtil.isNotBlank(contentType)) {
            String[] params = contentType.split(SEMICOLON);
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split(EQUALS, 2);
                    if (pair.length == 2) {
                        if (StrUtil.isNotBlank(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }

    /**
     * 由于HttpUrlConnection不支持设置KeepAlive超时时间，该方法通过反射机制设置
     *
     * @param connection 需要设置KeepAlive的连接
     */
    private void setKeepAliveTimeout(HttpURLConnection connection) {
        if (keepAliveTimeout == 0) {
            return;
        }
        try {

            Field delegateHttpsUrlConnectionField = Class.forName("sun.net.www.protocol.https.HttpsURLConnectionImpl").getDeclaredField(
                    "delegate");
            delegateHttpsUrlConnectionField.setAccessible(true);
            Object delegateHttpsUrlConnection = delegateHttpsUrlConnectionField.get(connection);

            Field httpClientField = Class.forName("sun.net.www.protocol.http.HttpURLConnection").getDeclaredField("http");
            httpClientField.setAccessible(true);
            Object httpClient = httpClientField.get(delegateHttpsUrlConnection);

            Field keepAliveTimeoutField = Class.forName("sun.net.www.http.HttpClient").getDeclaredField("keepAliveTimeout");
            keepAliveTimeoutField.setAccessible(true);
            keepAliveTimeoutField.setInt(httpClient, keepAliveTimeout);
        } catch (Throwable ignored) {
            //设置KeepAlive超时只是一种优化辅助手段，设置失败不应阻塞主链路，设置失败不应影响功能
        }
    }

}
